package cn.zhaoyuening.lucenedemo2.init;

import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexableField;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.ContextStartedEvent;
import org.springframework.web.WebApplicationInitializer;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
import java.io.IOException;

/**
 * Created by Zhao on 2017/2/26.
 */
public class LuceneIndexHandler implements ApplicationListener<ContextRefreshedEvent> {
    private IndexWriter indexWriter;


    @Autowired
    public void setIndexWriter(IndexWriter indexWriter) {
        this.indexWriter = indexWriter;
    }

    public void createIndexs() throws IOException {
        indexWriter.deleteAll();
        Document document = null;
        try {
            document = Jsoup.connect("http://news.sina.com.cn/").get();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Elements elements = document.select(".list_14_noBg li a");
        String html = elements.html();
        for (Element element : elements) {
            org.apache.lucene.document.Document luceneDoc = new org.apache.lucene.document.Document();

            IndexableField hrefField = new StringField("href",element.attr("href"), Field.Store.YES);
            IndexableField titleField = new TextField("title",element.html(),Field.Store.YES);

            luceneDoc.add(hrefField);
            luceneDoc.add(titleField);

            try {
                indexWriter.addDocument(luceneDoc);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }



    public void onApplicationEvent(ContextRefreshedEvent event) {

        try {
            createIndexs();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
